package com.trusfort.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.trusfort.redis.DBIndex;
import com.trusfort.redis.JedisClient;
import com.trusfort.redis.RedisConnectionPool;
import com.util.FileUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.ScanResult;

public class DataAnalysisService {

	
	  
	  private static String savePath = "D:/data/redis_exp/";
	  private static String limit = "2";
		
	  public  static	String[] redisKeys = { 
				"XDID::aaid", 
				"XDID::abid", 
				"XDID::absn",
				"XDID::afdid", 
				"XDID::asn", 
				"XDID::acid",
				"XDID::afit",
				"XDID::afdid",
				"XDID::afdidrand"
				};
	 
		private static void logInfo(String msg) {

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String cur = sdf.format(new Date());

			System.out.println(msg);
			
			FileUtils.write(savePath + "/logs/info.txt", cur + " [INFO] " + msg);
		}


		static void saveInvalidField(String fileName, String msg) {
			FileUtils.write(savePath + "/" + fileName + ".txt", msg);
		}
 
		
		/**
		 * 扫描Redis数据
		 * @param client
		 * @param key
		 * @param clear
		 * @throws Exception
		 */
		public static void scanRedisData(JedisClient client,String key)throws Exception {
			logInfo("  分析无效特征值  【" + key + "】 对应设备指纹数量开始>>");
			
			long total = 0;
			
			String pattern = key + "*";
			String scanRet = "0";
	        do {
	        	 ScanResult<String> result2 = client.scan(DBIndex.XDID_DB_INDEX, pattern, scanRet, 10000);

				java.util.List<String> keys = new ArrayList();

				String fileName = pattern.replace("*","").split("::")[1];
				
				java.util.List<String> list = result2.getResult();
				scanRet = result2.getStringCursor();
				if (list != null && !list.isEmpty()) {
					for (int j = 0; j < list.size(); j++) {
						keys.add(list.get(j));
					}
					scard(fileName, keys);
					total += list.size();
				}
	            
	        } while (!scanRet.equals("0"));
			
			
			logInfo("  分析无效特征值  【" + key + "】 对应设备指纹数量结束,共扫描 【"+total+" 】条<<");
		}

		/**
		 * 统计无效字段
		 */
		public static void dataAnalysis(String _savePath,String hosts,String _limit,String redisKeyPrefix,String passwd) {

			try {

				savePath = _savePath;
				limit = _limit;
				
				if(hosts == null) {
					return;
				}
				
				 String redisUsageMode = "single";
				 if(hosts.indexOf(",")!=-1) {
					 redisUsageMode = "cluster";
				 }
				 
				if(redisUsageMode.equals("single")) {

					String [] hostAndPort = hosts.split(":");
					
					JedisClient client = new JedisClient(hostAndPort[0],Integer.valueOf(hostAndPort[1]),passwd);

					logInfo("分析安卓无效特征值对应设备指纹 数量开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
					
					if("all".equals(redisKeyPrefix)) {
						for (String key : redisKeys) {
							scanRedisData(client,key);
						}
					}else {
						scanRedisData(client,redisKeyPrefix);
					}
					
					logInfo("分析安卓无效特征值对应设备指纹 数量结束");
				}

			} catch (Exception e1) {
			  e1.printStackTrace();
			}

		}

		
		static void scard(String fileName, java.util.List<String> list) throws Exception {

			// 管道返回的结果集

			java.util.List<Map<String, Object>> searchResult = new ArrayList<Map<String, Object>>();

			Jedis jedis = null;
			try {
				jedis = RedisConnectionPool.getInstance().getJedis(DBIndex.XDID_DB_INDEX);

				Pipeline pipeline = jedis.pipelined();

				for (String key : list) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("key", key);
					map.put("response", pipeline.scard(key));
					searchResult.add(map);
				}
				pipeline.sync();

				if (searchResult.size() > 0) {
					for (Map<String, Object> keyResult : searchResult) {

						Response<Long> resp = (Response<Long>) keyResult.get("response");

						String key = keyResult.get("key").toString();
						if (resp.get() >= Integer.valueOf(limit) && resp.get()<10) {
							
							Set<String> devids = jedis.smembers(key);
							saveInvalidField(fileName, "【" + key + "】对应设备指纹列表 共【"+resp.get()+"】条");	
							//循环输出devi和ttl
							for (String devid : devids) {
								long ttl = jedis.ttl("XDID::adid"+devid);
								if(ttl==-2) {
									saveInvalidField(fileName, "【" + key + "】>> "+devid+"-【不存在】");	
								}else {
									saveInvalidField(fileName, "【" + key + "】>> "+devid+"-【"+ttl+"】");	
								}
								
							}
						}
					}
				}
			} catch (Exception e) {
				throw e;
			} finally {
				RedisConnectionPool.getInstance().returnResource(jedis);
			}
		}
	
}
